package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.AbsService;

public class GoodsBaseServiceImpl extends AbsService {
	
	private Logger log = LoggerFactory.getLogger(GoodsBaseServiceImpl.class);
	
	public JSONObject getGoodsListByMealIds(String mealIds)  throws Exception {
		ApiUrl apiUrl = this.buildMallApiBaseUrl("MALL_MEAL_PARTIAL_LIST");
		String[] otherParams = {ApiUrlParamEnum.ids.getParamName(),mealIds};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[getGoodsListByIds] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),  Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取商品接口异常！");
		}
		return result;
	}
	
	/**
	 * 拼凑mealId串
	 * @param listJSONArray
	 * @return
	 */
	private String getMealIds(JSONArray listJSONArray){
		StringBuilder sb = new StringBuilder(); 
		for(int i= 0;i<listJSONArray.size() ;i++){
			JSONObject listJSONObject = (JSONObject)listJSONArray.get(i);
			sb.append(listJSONObject.getInteger("mealId"));
			if(i < listJSONArray.size()-1)
				sb.append(",");
		}
		return sb.toString();
	}
	
	
	/**
     * 根据购物车中的商品id，查询商品信息
     * @param jsonArray
     * @return
     */
    protected Map<Integer,JSONObject> getGoodsMap(JSONArray listJSONArray) throws Exception {
    	String mealIds = this.getMealIds(listJSONArray);
    	log.info("func[getGoodsMap] mealIds=" + mealIds);
    	JSONObject goodsList = this.getGoodsListByMealIds(mealIds);
		JSONArray goodsArrayJson = goodsList.getJSONObject("response").getJSONArray("list");
    	Map<Integer,JSONObject> goodsMap = new HashMap<Integer,JSONObject>();
    	if(null != goodsArrayJson ) {
    		for(Object goodsObject:goodsArrayJson){
    			JSONObject goods = (JSONObject)goodsObject;
    			goodsMap.put(goods.getInteger("mealId"), goods);
    		}
		}
    	return  goodsMap;
    }
    
    /**
     * 商品信息和jsonArray合并数据
     * @param jsonArray
     * @param goodsMap
     * @return
     */
    protected List<Map<String,Object>> mergeGoods (JSONArray jsonArray,Map<Integer,JSONObject> goodsMap){
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for(int j = 0; j<jsonArray.size(); j++) {
			JSONObject jsonObject = jsonArray.getJSONObject(j);
			JSONObject goodsJSONObject = goodsMap.get(jsonObject.getInteger("mealId"));
			Map<String,Object> infoMapObject= JSON.toJavaObject(jsonObject, Map.class);
			String browsingTime = jsonObject.getString("visitDay");//浏览时间
			if(null != browsingTime){
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(Long.parseLong(browsingTime));
				infoMapObject.put("browsingTime",DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd hh:mm:ss") );
				infoMapObject.put("browsingId",jsonObject.getString("id"));
				infoMapObject.put("userId",jsonObject.getString("userId"));
			}
			if(goodsJSONObject == null){
				list.add(infoMapObject);
				continue;
			}
			infoMapObject.put("ifGift",goodsJSONObject.getString("ifGift") );
			infoMapObject.put("coverImgPath",goodsJSONObject.getString("coverImgPath") );
			infoMapObject.put("title",goodsJSONObject.getString("title") );
			infoMapObject.put("minPrice",goodsJSONObject.getFloat("minPrice") );
			infoMapObject.put("factory",goodsJSONObject.getString("factory") );
			infoMapObject.put("normsName",goodsJSONObject.getString("normsName") );
			infoMapObject.put("prescriptionType", goodsJSONObject.getIntValue("prescriptionType"));
			list.add(infoMapObject);
		}
		return list;
    }
}
